<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0" v-if="list.length">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return {
      list: [
        { id: 1, name: 'tom', age: '18', gender: '男' },
        { id: 2, name: 'jack', age: '20', gender: '男' }
      ],
      name: '',
      age: '',
      gender: '',
      flage: false,
      indeId: 0
    }
  },
  methods: {
    // 删除
    del (id) {
      this.list = this.list.filter(item => item.id !== id)
    },

    // 判断是添加还是修改
    add () {
      // 修改
      if (this.flag) {
        this.list[this.indeId].name = this.name
        this.list[this.indeId].age = this.age
        this.list[this.indeId].gender = this.gender
        this.name = ''
        this.age = ''
      }
      // 添加
      else if (this.name && this.age && this.gender) {
        if (this.age >= 1) {
          const lists = {
            id: this.index + 1,
            name: this.name,
            age: this.age,
            gender: this.gender
          }

          this.list.push(lists)
          this.name = ''
          this.age = ''
        } else {
          alert('请输入正确年龄')
        }
      } else {
        alert('请输入必填项')
      }
    },
    // 编辑
    edit (index) {
      this.name = this.list[index].name
      this.age = this.list[index].age
      this.gender = this.list[index].gender
      this.indeId = index
      this.flag = true
    }
  }
}
</script>

<style scoped></style>





